package com.mo.modular.search.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.plugins.Page;
import com.mo.common.lucene.LuceneQueryManager;
import com.mo.common.lucene.LuceneWriterManager;
import com.mo.common.lucene.interfaceAction.LuceneReader;
import com.mo.common.lucene.interfaceAction.LuceneSave;
import com.mo.common.lucene.interfaceAction.LuceneUpdate;
import com.mo.common.lucene.utils.DocAndBeanUtils;
import com.mo.common.lucene.utils.LuceneClient;
import com.mo.search.model.MixedCont;
import com.mo.search.service.IWriteMixedService;

/**
 * 
 *
 * @author chenxiaodong
 * @date 2018-08-23 12:34
 */
@Service
public class WriteMixedServiceImpl implements IWriteMixedService {

	@Value("${path.lucenePath}")
	private String lucenePath;


	private LuceneWriterManager luceneWriterManager;

	private LuceneQueryManager luceneQueryManager;
	@Override
	public int save(MixedCont mixedCont) {
		try {
			luceneWriterManager.write(new LuceneSave() {
				@Override
				public Document write() throws Exception {
					Document doc = new Document();
					try {
						System.out.println(mixedCont.getContName());
						DocAndBeanUtils.toDocument(doc, mixedCont);
						doc.removeField("description");
						doc.add(new TextField("description",  mixedCont.getDescription(), org.apache.lucene.document.Field.Store.YES));
//						doc.add(new StringField("contName",  mixedCont.getContName(), org.apache.lucene.document.Field.Store.YES));
						doc.add(new StoredField("id", mixedCont.getId()));// 设置主键
						doc.add(new StoredField("contType", mixedCont.getContType()));// 设置主键
					} catch (Exception e) {
						e.printStackTrace();
					}
					return doc;
				}
			});
		} catch (IOException e) {
			e.printStackTrace();
		}
		return 1;
	}
	@Override
	public int initLucene(MixedCont mixedCont) {
		luceneQueryManager = new LuceneQueryManager(new LuceneClient(lucenePath));
		LuceneReader<List<MixedCont>> reader = new LuceneReader<List<MixedCont>>() {
			@SuppressWarnings("unchecked")
			@Override
			public List<MixedCont> read( IndexSearcher indexSearcher, TopDocs topDocs)throws Exception {
				return (List<MixedCont>) DocAndBeanUtils.toBeanList(indexSearcher, topDocs.scoreDocs, MixedCont.class);
			}
		};
		//进行精确查找
		List<MixedCont> av = new ArrayList<MixedCont>();
		try {
			av = luceneQueryManager.readForTermQuery(reader, "id", mixedCont.getId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		luceneWriterManager = LuceneWriterManager.getInstance(lucenePath);
		if(av.size()>0){
			update(mixedCont);
		} else{
			save(mixedCont);
		}
		return 1;
	}
	@Override
	public int del(String id, String contType) {

		luceneWriterManager = LuceneWriterManager.getInstance(lucenePath);
		String searchField = "title";
		// 删除title中含有关键词“Spark”的文档
		TermQuery query = new TermQuery(new Term(searchField, "chenSpark4"));
		try {
			long count = luceneWriterManager.delete(query);
			System.out.println(count);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public int update(MixedCont mixedCont) {

		luceneWriterManager = LuceneWriterManager.getInstance(lucenePath);
		luceneWriterManager.updateByMajorKey(new LuceneUpdate() {
			@Override
			public Document updateByMajorKey() throws Exception {
				Document doc = new Document();
				DocAndBeanUtils.toDocument(doc, mixedCont);
				doc.removeField("description");
				doc.add(new TextField("description",  mixedCont.getDescription(), org.apache.lucene.document.Field.Store.YES));
//				doc.add(new StringField("contName",  mixedCont.getContName(), org.apache.lucene.document.Field.Store.YES));
				doc.add(new StoredField("id", mixedCont.getId()));// 设置主键
				doc.add(new StoredField("contType", mixedCont.getContType()));// 设置主键
				return doc;
			}
		}, "contName");// 、、,"id"
		return 0;
	}

	@Override
	public int updateAllList(String contType) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int updateAllMixedCont() {
		try {
			Date startTime = new Date();
			System.out.println("创建索引开始---------------------当前时间为" + startTime);
			Integer videoPage = 1;
			Integer videoPageSize = 50;

			// 1.视频相关
			while (true) {
				Page<MixedCont> page = new Page<MixedCont>(videoPage, videoPageSize);
				Map<String,String> paramMap = new HashMap<String, String>();
//				paramMap.put("contType", ContTypeEnum.VIDEO.getCode()+"");
				paramMap.put("imgPlat", "android");
				paramMap.put("playUrlPlat", "mobilemo");
				/*Page<MixedCont> allMobileContForPage = contService
						.getAllMobileContByPageInfo(paramMap,page);
				List<MixedCont> allMobileContByPageInfo = allMobileContForPage.getRecords();
				if (allMobileContByPageInfo != null
						&& allMobileContByPageInfo.size() > 0) {
					getDvUserInfo(allMobileContByPageInfo);
					for (MixedCont mc : allMobileContByPageInfo) {
						System.out.println(mc.getContName() + "----" + mc.getDescription());
						initLucene(mc);
					}
					System.out.println("当前页码为:" + videoPage);
					videoPage++;
				} else {
					break;
				}*/
				break;
			}

			

			Date endTime = new Date();
			System.out.println("创建索引结束---------------------当前时间为：" + endTime
					+ ",总时长为：" + (endTime.getTime() - startTime.getTime())
					+ "毫秒");
			return 1;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}

	}

}
